package com.lsf.config.shiro;

import com.lsf.config.shiro.filters.CustomShiroFilterFactoryBean;
import com.lsf.config.shiro.filters.JwtFilter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.crazycake.shiro.IRedisManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisClusterManager;
import org.crazycake.shiro.RedisManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import javax.annotation.Resource;
import javax.servlet.Filter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Shiro配置类
 *
 * @author Alexander
 */
@Configuration
@Slf4j
public class ShiroConfig {

    @Value("${mikou.shiro.excludeUrls}")
    private String excludeUrls;
    @Resource
    private LettuceConnectionFactory lettuceConnectionFactory;

    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        CustomShiroFilterFactoryBean shiroFilterFactoryBean = new CustomShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //拦截器
        LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        if (StringUtils.isNotEmpty(excludeUrls)) {
            String[] permissionUrl = excludeUrls.split(",");
            for (String url : permissionUrl) {
                filterChainDefinitionMap.put(url, "anon");
            }
        }
        //配置不被拦截的URL 顺序判断
        //cas验证登录
        filterChainDefinitionMap.put("/sys/cas/client/validateLogin", "anon");
        //登录验证码接口排除
        filterChainDefinitionMap.put("/sys/randomImage/**", "anon");
        //登录验证码接口排除
        filterChainDefinitionMap.put("/sys/checkCaptcha", "anon");
        //登录接口排除
        filterChainDefinitionMap.put("/sys/login", "anon");
        //登录接口排除
        filterChainDefinitionMap.put("/sys/mLogin", "anon");
        //登出接口排除
        filterChainDefinitionMap.put("/sys/logout", "anon");
        //第三方登录
        filterChainDefinitionMap.put("/sys/thirdLogin/**", "anon");
        //获取加密串
        filterChainDefinitionMap.put("/sys/getEncryptedString", "anon");
        //短信验证码
        filterChainDefinitionMap.put("/sys/sms", "anon");
        //手机登录
        filterChainDefinitionMap.put("/sys/phoneLogin", "anon");
        //校验用户是否存在
        filterChainDefinitionMap.put("/sys/user/checkOnlyUser", "anon");
        //用户注册
        filterChainDefinitionMap.put("/sys/register", "anon");
        //邮件验证码
        filterChainDefinitionMap.put("/sys/sendEmail", "anon");
        //用户忘记密码验证手机号
        filterChainDefinitionMap.put("/sys/user/phoneVerification", "anon");
        //用户更改密码
        filterChainDefinitionMap.put("/sys/user/passwordChange", "anon");
        //登录验证码
        filterChainDefinitionMap.put("/auth/2step-code", "anon");
        //图片预览 &下载文件不限制token
        filterChainDefinitionMap.put("/sys/common/static/**", "anon");
        filterChainDefinitionMap.put("/", "anon");
        filterChainDefinitionMap.put("/doc.html", "anon");
        filterChainDefinitionMap.put("/**/*.js", "anon");
        filterChainDefinitionMap.put("/**/*.css", "anon");
        filterChainDefinitionMap.put("/**/*.html", "anon");
        filterChainDefinitionMap.put("/**/*.svg", "anon");
        filterChainDefinitionMap.put("/**/*.pdf", "anon");
        filterChainDefinitionMap.put("/**/*.jpg", "anon");
        filterChainDefinitionMap.put("/**/*.png", "anon");
        filterChainDefinitionMap.put("/**/*.ico", "anon");

        //排除字体格式的后缀
        filterChainDefinitionMap.put("/**/*.ttf", "anon");
        filterChainDefinitionMap.put("/**/*.woff", "anon");
        filterChainDefinitionMap.put("/**/*.woff2", "anon");

        filterChainDefinitionMap.put("/druid/**", "anon");
        filterChainDefinitionMap.put("/swagger-ui.html", "anon");
        filterChainDefinitionMap.put("/swagger**/**", "anon");
        filterChainDefinitionMap.put("/webjars/**", "anon");
        filterChainDefinitionMap.put("/v2/**", "anon");

        filterChainDefinitionMap.put("/sys/annountCement/show/**", "anon");

//        以后关
        filterChainDefinitionMap.put("/sys/article/add", "anon");
        filterChainDefinitionMap.put("/sys/comment/add", "anon");
        filterChainDefinitionMap.put("/sys/follow/add", "anon");
        filterChainDefinitionMap.put("/sys/index/queryFollowList", "anon");

        //websocket排除
        //系统通知和公告
        filterChainDefinitionMap.put("/websocket/**", "anon");
        //CMS模块
        filterChainDefinitionMap.put("/newsWebsocket/**", "anon");
        //JVxeTable无痕刷新示例
        filterChainDefinitionMap.put("/vxeSocket/**", "anon");

        //添加自己的过滤器并且取名为jwt
        Map<String, Filter> filterMap = new HashMap<>(1);
        filterMap.put("jwt", new JwtFilter(true));
        shiroFilterFactoryBean.setFilters(filterMap);
        //过滤链定义,从上向下顺序执行,一般将/**放在最下边
        filterChainDefinitionMap.put("/**", "jwt");

        //未授权界面返回json
        shiroFilterFactoryBean.setUnauthorizedUrl("/sys/common/403");
        shiroFilterFactoryBean.setLoginUrl("/sys/common/403");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

    @Bean("securityManager")
    public DefaultWebSecurityManager securityManager(ShiroRealm realm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm);

        //关闭Shiro自带的session
        DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
        DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
        defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
        subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
        securityManager.setSubjectDAO(subjectDAO);
        //自定义缓存实现,使用redis
        securityManager.setCacheManager(redisCacheManager());
        return securityManager;
    }

    /**
     * cacheManager缓存redis实现
     *
     * @return {@link RedisCacheManager}
     */
    public RedisCacheManager redisCacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(redisManager());
        //redis中针对不同的用户缓存(此处的id需要对应user实体中的id字段,用于唯一标识)
        redisCacheManager.setPrincipalIdFieldName("id");
        //用户权限信息缓存时间
        redisCacheManager.setExpire(200000);
        return redisCacheManager;
    }

    /**
     * 配置shiro redisManager
     * 使用的是shiro-redis开源插件
     *
     * @return {@link IRedisManager}
     */
    @Bean
    public IRedisManager redisManager() {
        IRedisManager manager;
        //redis单机支持
        if (lettuceConnectionFactory.getClusterConfiguration() == null || lettuceConnectionFactory.getClusterConfiguration().getClusterNodes().isEmpty()) {
            RedisManager redisManager = new RedisManager();
            redisManager.setHost(lettuceConnectionFactory.getHostName());
            redisManager.setPort(lettuceConnectionFactory.getPort());
            redisManager.setDatabase(lettuceConnectionFactory.getDatabase());
            redisManager.setTimeout(0);
            if (StringUtils.isNotEmpty(lettuceConnectionFactory.getPassword())) {
                redisManager.setPassword(lettuceConnectionFactory.getPassword());
            }
            manager = redisManager;
        } else {
            //redis集群支持,优先使用集群配置
            RedisClusterManager redisManager = new RedisClusterManager();
            HashSet<HostAndPort> portSet = new HashSet<>();
            lettuceConnectionFactory.getClusterConfiguration().getClusterNodes().forEach(redisNode -> portSet.add(new HostAndPort(redisNode.getHost(), redisNode.getPort())));
            //修改集群模式下未设置redis密码的Bug
            if (StringUtils.isNotEmpty(lettuceConnectionFactory.getPassword())) {
                JedisCluster jedisCluster = new JedisCluster(portSet, 2000, 2000, 5, lettuceConnectionFactory.getPassword(), new GenericObjectPoolConfig());
                redisManager.setPassword(lettuceConnectionFactory.getPassword());
                redisManager.setJedisCluster(jedisCluster);
            } else {
                JedisCluster jedisCluster = new JedisCluster(portSet);
                redisManager.setJedisCluster(jedisCluster);
            }
            manager = redisManager;
        }
        return manager;
    }


    /**
     * 下面的代码是添加注解支持的
     *
     * @return {@link DefaultAdvisorAutoProxyCreator}
     */
    @Bean
    @DependsOn("lifecycleBeanPostProcessor")
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
        /**
         * 解决重复代理问题
         * 添加前缀判断 不匹配任何Advisor
         */
        defaultAdvisorAutoProxyCreator.setUsePrefix(true);
        defaultAdvisorAutoProxyCreator.setAdvisorBeanNamePrefix("_no_advisor");
        return defaultAdvisorAutoProxyCreator;
    }

    @Bean
    public static LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }

}
